<template>
  <div class="box">
    <el-form :model="loginForm" :rules="loginRules" :ref="loginForm" label-width="100px">
      <div class="sysName">astre{{$t('backmansys')}}</div>
      <el-form-item prop="userid">
        <el-input v-model.trim="loginForm.userid" :placeholder="$t('username')"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model.trim="loginForm.password" :placeholder="$t('password')" show-password @keyup.enter.native="login(loginForm)"></el-input>
      </el-form-item>
      <el-button type="primary" round style="width: 416px" @click="login(loginForm)" :loading="loading">{{$t('login')}}</el-button>
    </el-form>
  </div>
</template>

<script>
import { userLogin } from '@/libs/reqlist.js'
import Cookie from 'js-cookie'
export default {
  data () {
    return {
      // 图片验证码地址
      imgCodeSrc: '',
      // 登录表单数据
      loginForm: {
        userid: '',
        password: ''
      },
      // 登录表单验证
      loginRules: {
        userid: [
          { required: true, message: this.$t('plsentusername'), trigger: 'blur'}
        ],
        password: [
          { required: true, message: this.$t('plsentuserpwd'), trigger: 'blur'}
        ]
      },
      loading: false
    }
  },
  methods: {
    login (form) {
      this.$refs[form].validate(async valid => {
        if (!valid) return
        this.loading = true
        userLogin(JSON.stringify(this.loginForm)).then(res => {
          this.loading = false
          if (res.data.code == 0) {
            window.localStorage.setItem('jounery', this.loginForm.userid)
            this.$store.commit('setToken', res.data.data.tokenHead + res.data.data.token)
            this.$router.push('/home')
            this.$store.commit('setUserID', res.data.data.id)
            this.$store.commit('setUserRole', res.data.data.roles)
            let date = new Date().getTime()
            window.sessionStorage.setItem('refTime', date)
          }
        })
      })
    }
  },
  mounted () {
    let defLang = 'zh-CN'  // navigator.language
    Cookie.set('language', defLang)
    if (window.sessionStorage.getItem('activePath')) window.sessionStorage.removeItem('activePath')
    if (window.localStorage.getItem('jounery')) this.loginForm.userid = window.localStorage.getItem('jounery')
  }
}
</script>

<style lang="less" scoped>
@import "./login.less";
</style>
